package com.DosonLeung.homeschoolcommunication.Models;

import android.util.Log;

import com.DosonLeung.homeschoolcommunication.Constant.UrlConstant;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by xujiachong on 14/12/2.
 */
public class MessageModel {

    public static void getHistoryMessage(final String account,final String password) {
        AsyncHttpClient client = new AsyncHttpClient();
        String url = UrlConstant.getHistoryMessageUrl;
        RequestParams params = new RequestParams();
        params.put("account",account);
        params.put("password",password);
        System.out.print("getgetget");
        client.post(url, params, new JsonHttpResponseHandler() {

            @Override
            public void onFinish() {
                // TODO Auto-generated method stub
                super.onFinish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {
                    JSONObject data = response.getJSONObject("data");
                    JSONArray arr = data.getJSONArray("messages");
                    for(int i = 0; i < arr.length(); i++) {
                        String tmp = arr.get(i).toString();
                        JSONObject obj = new JSONObject(tmp);
                        MessageModel.receivedMessage(obj);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                //MessageModel.getHistoryMessage(account,password);
            }
        });
    }

    /**
     * 获得每条历史消息的JSON都会调用这个方法，Ps.需要的参数自行添加
     * @param msgObj json
     */
    private static void receivedMessage(JSONObject msgObj) {
        Log.v("getJson",msgObj.toString());

    }

}
